var page = {
    init: function () {
        $('#unpublish-product').on('click', page.unpublishedProduct);
        $('#delete-product').on('click', page.deleteProduct);
        $('#publish-product').on('click', page.publishedProduct);

        $('#form').on('submit', page.submitEvents);

        page.cityHunterProductEvents();
    },
    cityHunterProductEvents: function () {
        page.departPlaceEvents();
        page.similarPruductEvents();
        page.instructionEvents();
        page.productDetailEvents();
        page.subProductEvents();
        // page.mapEvents();
        page.productTabEvents();
        page.languageEvents();
        page.durationEvents();
        page.descriptionEvents();
        page.cityHunterEvents();
        page.photoEvents();
        page.tabEvents();

        mapMeet = new page.MapEvents({
            map: page.mapMeet,
            dom: 'map-meet',
            $lat: $('#id_latitude'),
            $lng: $('#id_longitude'),
            marker: page.markerMeet
        });

        mapAddress = new page.MapEvents({
            map: page.mapAddress,
            dom: 'map-address',
            $lat: $('#id_address_latitude'),
            $lng: $('#id_address_longitude'),
            marker: page.markermapAddress
        });

    },
    inArray: function (item, arr){
        for(var i = 0; i < arr.length; i++){
            if(arr[i] == item){
                return true;
            }
        }
    },
    newWindowFeatures: function () {
        var sh = window.screen.height, sw = window.screen.width, width=800, height=600;
        var left = (sw - width) / 2, top = (sh - height) / 2;
        var features = 'width=' + width + ',height=' + height + ',top=' + top + ',left=' + left;
        features += ',toolbar=no, status=no, menubar=no, channelmode=yes, fullscreen=yes';
        return features;
    },
    addProductInstruction: function (e){
        e.preventDefault();
        window.open(url.PRODUCT_INSTRUCTION_CREATE, '', page.newWindowFeatures);
    },
    move2Instruction: function (detailPk){
        $.post('./movedetail2instruction/', {
            'detail_pk': detailPk
        }, function(data){
            if (data.success) {
                page.appendInstruction(data.pk, data.title);
                page.deleteProductDetail(detailPk);
            } else {
                alert(data.error);
            }
        }, 'json');
    },
    appendInstruction: function (pk, title){
        if ($('#ins-' + pk)[0]) {
            $('#ins-' + pk).find('a.name').text(title);
        } else {
            var ids = $('#id_instructions').val().split(',');
            ids.push(pk);
            $('#id_instructions').val(ids.join(','));

            var html = '<li id="ins-' + pk + '" data-pk="' + pk +
                    '"><a class="name" target="_blank" href="/dashboard/tp/product-instruction/' +
                    pk + '/">' + title +
                    '</a><a class="close" onclick="page.deleteInstruction(' + pk +
                    ')">&times;</a></li>';
            $('#instruction-panel').append(html);
        }
    },
    deleteInstruction: function (pk){
        $('#ins-' + pk).remove();
        var content = $('#id_instructions').val();
        $('#id_instructions').val(content.replace(pk, ''));
    },
    instructionEvents: function () {
        $('#add-instruction').on('click', page.addProductInstruction);
        $('#instruction-panel').sortable({
            stop: function(event, ui){
                var ids = [];
                $('#instruction-panel').find('li').each(function(){
                    var e = $(this);
                    ids.push(e.data('pk'));
                });
                $('#id_instructions').val(ids.join(','));
            }
        });
        $('#instruction-panel').disableSelection();
    },
    deleteProductDetail: function (pk){
        $('#pd-' + pk).remove();
        var content = $('#id_details').val();
        $('#id_details').val(content.replace(pk, ''));
    },
    deleteProduct: function (){
        $('#form-delete').submit();
    },
    addProductDetail: function (e){
        e.preventDefault();
        window.open(url.PRODUCT_DETAIL_CREATE, '', page.newWindowFeatures);
    },
    appendProductDetail: function (pk, title){
        if ($('#pd-' + pk)[0]) {
            $('#pd-' + pk).find('a.name').text(title);
        } else {
            var ids = $('#id_details').val().split(',');
            ids.push(pk);
            $('#id_details').val(ids.join(','));

            var html = '<li id="pd-' + pk + '" data-pk="' + pk +
                    '"><a class="name" target="_blank" href="/dashboard/tp/product-detail/' +
                    pk + '/">' + title + '</a>' +
                    '<a class="close" onclick="page.deleteProductDetail(' + pk +
                    ')">&times;</a>' +
                    '<a href="###" class="label pull-right" onclick="page.move2Instruction(' + pk +
                    ')" style="margin-right:10px;">迁移到亮点推荐</a>' +
                    '</li>';
            $('#description ul').append(html);
        }
    },
    productDetailEvents: function () {
        $('#add-product-detail').on('click', page.addProductDetail);
    },
    descriptionEvents: function () {
        $('#description-panel').sortable({
            stop: function(event, ui){
                var ids = [];
                $('#description-panel').find('li').each(function(){
                    var e = $(this);
                    ids.push(e.data('pk'));
                });
                $('#id_details').val(ids.join(','));
            }
        });
        $('#description-panel').disableSelection();
    },

    cityHunterEvents: function () {
        $('#cityhunter_sel').select2();
    },

    deleteTrip: function (pk){
        $('#trip-' + pk).remove();
        var ids = $('#id_related_trips').val();
        $('#id_related_trips').val(ids.replace(pk, ''));
    },
    addSubProduct: function (e){
        e.preventDefault();
        window.open(url.SUB_PRODUCT, page.newWindowFeatures);
    },
    appendSubProduct: function (pk, title){
        if ($('#sub-product-' + pk)[0]) {
            $('#sub-product-' + pk).find('a.name').text(title);
        } else {
            var ids = $('#id_sub_products').val().split(',');
            ids.push(pk);
            $('#id_sub_products').val(ids.join(','));

            var html = '<li id="sub-product-' +
                       pk + '" data-pk="' + pk +
                       '"><a class="name" target="_blank" href="/dashboard/tp/sub_product/?id=' +
                       pk + '&category='+ CATEGORY +'">' +
                       title + '</a><a class="close" onclick="page.deleteSubProduct(' + pk +
                       ')">&times;</a></li>';
            $('#sub-product-panel').append(html);
        }
    },
    deleteSubProduct: function (pk){
        $('#sub-product-' + pk).remove();
        var ids = $('#id_sub_products').val();
        $('#id_sub_products').val(ids.replace(pk, ''));
    },
    subProductEvents: function () {
        $('#add-sub-product').on('click', page.addSubProduct);
        $('#sub-product-panel').sortable({
            stop: function(event, ui){
                var ids = [];
                $('#sub-product-panel').find('li').each(function(){
                    var e = $(this);
                    ids.push(e.data('pk'));
                });
                $('#id_sub_products').val(ids.join(','));
            }
        });
        $('#sub-product-panel').disableSelection();
    },
    addSimilarProduct: function (title, id){
        var html = '<div class="alert alert-success" data-id="' +
            id + '"><button type="button" class="close" data-dismiss="alert">&times;</button><a target="_blank" href="/tp/customization/' + id + '/">' +
            title + '</a></div>';
        $('#similarProduct').append($(html));
    },
    selectSimilarProduct: function (){
        var title = $('#similarProductName').val(),
            id = title.split('.')[1],
            input = $('#id_similar_product'),
            value = input.val() || [];
        page.addSimilarProduct(title, id);
        value.push(id);
        input.val(value);
        $('#similarProductName').val('');
    },
    listAllSimilarProduct: function (){
        $('body').css('overflow', 'hidden');
        if ($('#similarProduct .alert-success').length >= 5) {
            alert('已经5个了，不能再多了');
            return;
        }
        setTimeout(function(){
            $('#similarProductName').autocomplete('search', 'No.');
        }, 1500);
    },
    similarPruductEvents: function () {
        $('#add-similar-product').on('click', page.listAllSimilarProduct);
        $('#select-similar-product').on('click', page.selectSimilarProduct);
        var similar = $('#id_similar_product').val() || [];
        for(var i = 0; i < similar.length; i++){
            var p = $('#id_similar_product').find('[value=' + similar[i] + ']');
            page.addSimilarProduct(p.text(), similar[i]);
        }

        // 删除相关旅行产品时的操作
        $('#similarProduct').find('.alert').on('closed', function(){
            var droppedId = $(this).data('id'),
                ids = $('#id_similar_product').val(),
                newIds = [];

            for(var i in ids){
                if(ids[i] == droppedId){
                    continue;
                }
                newIds.push(ids[i]);
            }
            $('#id_similar_product').val(newIds);
        });

        // 自动补全相关旅行产品
        page.names = [];
        $('#id_similar_product option').each(function(){
            var opt = $(this);
            page.names.push('No.' + opt.val() + '. ' + opt.text());
        });

        $('#manageSimilarProduct').on('hide', function(){
            $('body').css('overflow', 'auto');
            $('#similarProductName').autocomplete('close');
        }).on('shown', function(){
            if($('#similarProduct .alert-success').length >= 5){
                $('#manageSimilarProduct').modal('hide');
            }
        });

        $('#similarProductName').autocomplete({
            source: page.names,
            close : function(event, ui){
                $('body').css('overflow', 'auto');
                var name = $('#similarProductName').val();
                if(name.indexOf('No.') > -1) {
                    page.selectSimilarProduct();
                    $('#manageSimilarProduct').modal('hide');
                }
            }

        });
    },
    saveDepartPlace: function (){
        var value = [];
        $('#selectedDepartPlacePanel').html('');
        $('#departPlacePanel li').each(function(){
            var e = $(this);
            if(e.hasClass('selected')){
                value.push(e.text());
                $('#selectedDepartPlacePanel').append(e.clone());
            }
        });
        $('#id_depart_places').val(value.join(','));
        $('#manageDepartPlace').modal('hide');
    },
    departPlaceEvents: function () {
        page.initDepartPlace();
        $('#save-depart-place').on('click', page.saveDepartPlace);
        $('#departPlacePanel').on('click', 'li',function(){
            var e = $(this);
            if (e.hasClass('selected')) {
                e.removeClass('selected');
            } else {
                e.addClass('selected');
            }
        });
        $('#id_depart_places').parents('.controls').find('.error').addClass('hide');
    },
    initDepartPlace: function (){
        var selectedPlaces = $('#id_depart_places').val().split(',');
        $('#departPlacePanel li').each(function(){
            var e = $(this);
            if (page.inArray(e.text(), selectedPlaces)) {
                e.addClass('selected');
                $('#selectedDepartPlacePanel').append(e.clone());
            }
        });
    },
    unpublishedProduct: function (e){
        e.preventDefault();
        if (confirm('确定？')) {
            $.post(url.PUBLISH, {
                'csrfmiddlewaretoken': $('#form input[name=csrfmiddlewaretoken]').val(),
                'product_id': $('#productId').val(),
                'action': 'unpublish'
            }, function(data){
                if(data.code === 1){
                    window.location.reload();
                } else {
                    alert('下线失败：' + data.msg);
                }
            }, 'json');
        }
    },
    publishedProduct: function (e) {
        e.preventDefault();
        if (confirm('确定发布产品？')) {
            $.post(url.PUBLISH, {
                'csrfmiddlewaretoken': $('#form input[name=csrfmiddlewaretoken]').val(),
                'product_id': $('#productId').val(),
                'action': 'published'
            }, function(data){
                if(data.code === 1){
                    window.location.reload();
                } else {
                    var content = '';
                    $.each(data.data.form_errors, function(key, val) {
                        content += '<dt>' + key + '</dt>' + '<dd>' + val + '</dd>';
                    });
                    $('#alert dl').html(content);
                    page.showAlert();
                }
            }, 'json');
        }
    },
    showAlert: function () {
        $('#alert').show().affix();
    },
    hideAlert: function () {
        $('#alert').hide();
    },
    triggerLanguageInput: function () {
        var checkedInputs = $('#language input:checked'),
            ids = [];
        $.each(checkedInputs, function(i, val) {
            var name = $(val).attr('data-name');
            ids.push(name);
        });
        $('#id_langauges').val(ids.join(','));
    },
    languageEvents: function () {
    // City Hunter 语言
        page.triggerLanguageInput();
        $('#language input').on('change', page.triggerLanguageInput);
    },
    triggerProductTabInput: function () {
        var checkedInputs = $('#prodcut-tab input:checked'),
            ids = [];
        $.each(checkedInputs, function(i, val) {
            var id = $(val).attr('data-id');
            ids.push(id);
        });
        console.log(ids);
        $('#id_product_tabs').val(ids.join(','));
    },
    productTabEvents: function () {
    // City Hunter 属性标签
        page.triggerProductTabInput();
        $('#prodcut-tab input').on('change', page.triggerProductTabInput);
    },
    MapEvents: function (opts) {
        // if (map.size()) {
            var initialize = function () {
                var targetLat = opts.$lat.val(),
                    targetLng = opts.$lng.val(),
                    zoom = 16,
                    initOptions = {
                        zoom: zoom,
                        maxZoom: 18,
                        minZoom: 3,
                        mapTypeId: google.maps.MapTypeId.ROADMAP
                    };
                opts.map = bt.gmap.createMap(opts.dom, initOptions);

                if ( targetLat ) {
                    bt.gmap.setCenter(opts.map, targetLat, targetLng);
                    page.placeMarker(opts.map, targetLat, targetLng, opts);
                }else{
                    bt.gmap.zoomToChina(opts.map);
                }

                bt.gmap.addListener(opts.map, 'click', function(event) {
                    page.placeMarker(opts.map, event.latLng.lat(), event.latLng.lng(), opts);
                });
            };
            bt.gmap.initMapScript(initialize);
        // }
        var searchMap = function () {
            var address = $('#'+opts.dom).prev('.search').find('input').val();
            page.mapSearchEvents(address, opts);
        };
        $('#'+opts.dom).prev('.search').find('a').on('click', function (e) {
            e.preventDefault();
            searchMap();
        });
        $('#'+opts.dom).prev('.search').find('input').on('keydown', function (e) {
            if(e.keyCode == 13) {
                searchMap();
                return false;
            }
        });
    },
    mapSearchEvents: function (address, opts) {
        if($.trim(address)) {
            bt.gmap.searchAddress(opts.map, address, function(result) {
                var latLng = result[0].geometry.location;
                page.placeMarker(opts.map, latLng.lat(), latLng.lng(), opts);
            });
        }
    },
    placeMarker : function(map, lat, lng, opts) {
        if(google) {
            if (opts.marker) {
                opts.marker.setMap(null);
            }

            opts.marker = bt.gmap.createMarker({
                draggable: true,
                animation: google.maps.Animation.DROP,
                position: bt.gmap.createLatLng(lat, lng),
                map: map,
                zIndex: google.maps.Marker.MAX_ZINDEX
            });

            page.updateMarkerLocation(lat, lng, opts);
            bt.gmap.addListener(opts.marker, 'dragend', function () {
                page.updateMarkerLocation(lat, lng, opts);
            });
        }
    },
    updateMarkerLocation : function (lat, lng, opts) {
        var latLng = opts.marker.getPosition();
        opts.$lat.val(latLng.lat());
        opts.$lng.val(latLng.lng());
    },
    durationEvents: function () {
        var $min = $('#id_duration_min'),
            $max = $('#id_duration_max'),
            triggerMaxValue = function () {
                var value = $(this).val();
                if ($max.data('disable') !== true) {
                    $max.val(value);
                }
            },
            disableTrigger = function () {
                $max.attr('data-disable', true);
            };
        $min.on('keyup', triggerMaxValue);
        $max.on('keyup', disableTrigger);
    },
    changePhotosInput: function (val) {
        page.appendPhoto(val.photo_s);
        $.fancybox.close();
    },
    appendPhoto: function (photoUrl) {
        var ids = $('#photos').val().split('\n');
        ids.push(photoUrl);
        $('#photos').val(ids.join('\n'));
        page.showPhotos(photoUrl);
    },
    showPhotos: function (photoUrl) {
        var html = '<span id="photo-url-' + photoUrl + '" data-pk="' + photoUrl + '"><img style="width: 90px; height: 60px; margin-left:15px; margin-bottom:15px;" src="' + photoUrl + '" />' +
                '<a onclick="page.deletePhoto(\''+photoUrl+'\')">&times;</a></span>';

        $('#photoList').append(html);
    },
    deletePhoto: function (photoUrl){
        var parent = document.getElementById('photoList');
        var child = document.getElementById('photo-url-' + photoUrl);
        parent.removeChild(child);
        var ids = $('#photos').val();
        $('#photos').val(ids.replace(photoUrl + '\n', ''));
        $('#photos').val(ids.replace(photoUrl, ''));
    },
    photoEvents: function () {
        // 初始化显示图片
        var photoList = document.getElementById('photos').value.split('\n');
        for(var i = 0; i < photoList.length; i++){
            if(photoList[i].length > 0 && photoList[i] != 'None'){
                page.showPhotos(photoList[i]);
            }
        }

        // 上传图片浮层
        // $('a#upload_photo').bind('click', function() {
        //     $('a#upload_photo').fancybox({
        //         type: 'iframe',
        //         title: 'upload_photo',
        //         width: '420px',
        //         height: '200px',
        //         autoSize: false,
        //         helpers: {
        //             overlay: {
        //                 showEarly: true
        //             }
        //         }
        //     });
        // });

        // 拖拽图片
        $('#photoList').sortable({
            stop: function(event, ui){
                var ids = [];
                $('#photoList').find('span').each(function(){
                    var e = $(this);
                    ids.push(e.data('pk'));
                });
                $('#photos').val(ids.join('\n'));
            }
        });
    },
    submitEvents: function (e) {
        e.preventDefault();
        var title = $('#id_title').val();


        if (title === '') {
            alert('请填写标题');
            return false;
        }

        var data = $(this).serialize();
        $.ajax({
            url: '',
            type: 'POST',
            dataType: 'json',
            data: data,
            success: function (data) {
                var code = data.code;
                if (code === 1) {
                    alert('保存成功');
                    var id = data.data.product_id,
                        val = $('#productId').val();
                    if (val === '') {
                        var url = window.location.href + '?product_id=' + id;
                        window.location.href = url;
                    }
                    page.hideAlert();
                } else {
                    alert(data.msg);
                }
            }
        });
    },
    tabEvents: function () {
        $('#tabbable a[data-toggle="tab"]').on('shown', function () {
            mapMeet = new page.MapEvents({
                map: page.mapMeet,
                dom: 'map-meet',
                $lat: $('#id_latitude'),
                $lng: $('#id_longitude'),
                marker: page.markerMeet
            });

            mapAddress = new page.MapEvents({
                map: page.mapAddress,
                dom: 'map-address',
                $lat: $('#id_address_latitude'),
                $lng: $('#id_address_longitude'),
                marker: page.markermapAddress
            });
        })
    },
};

page.init();

